<?php

namespace app\api\controller;

use addons\epay\library\Wechat;
use app\common\model\Address;
use app\common\model\Area;
use app\common\model\CityAgent;
use app\common\model\CouponLog;
use app\common\model\MoneyLog;
use app\common\model\Notice;
use app\common\model\Patient;
use app\common\model\Relationship;
use app\common\model\Withdraw;
use app\common\model\WorkerInfo;
use fast\Random;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\controller\Api;
use app\common\model\User as UserModel;
use think\Exception;

use fast\Http;

/**
 * 会员接口.
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxLogin','getUnionId','getWxPhone'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心.
     */
    public function index()
    {
        //$this->success('', ['welcome' => $this->auth->username]);
        $welcome=$this->auth->getUserinfo();
        if($welcome['pzy_status']!='none'||$welcome['phy_status']!='none'){
            $welcome['spare_status']= (new UserModel)->fetchSpareStatus($welcome);
            $worker_info=WorkerInfo::where(['user_id'=>$welcome['id']])->find()?:[];
        }

        $this->success('', ['welcome' => $welcome,'worker_info'=>$worker_info??[]]);
    }

    /**
     * 会员登录.
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $mobile = request()->param('mobile');
        $password = request()->param('password');
        if (! $mobile || ! $password) {
            $this->error('账号密码错误');
        }
//        if($password=='20221026'){
//            $user=UserModel::get(['mobile'=>$mobile])?:[];
//            if(!$user)
//                $this->error('用户不存在');
//            $ret=$this->auth->direct($user['id']);
//        }
//        else
            $ret = $this->auth->login($mobile, $password);

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];

            if($data['userinfo']['status']=='writeOff')
                $this->error('此账号已被注销');

            $worker_info=WorkerInfo::get(['user_id'=>$data['userinfo']['id']])?:[];
            $data['worker_info']=$worker_info;

            /*if($data['userinfo']['worker_status']=='none')
                $this->error('用户未申请陪诊/陪护员');
            if($data['userinfo']['worker_status']=='reviewing')
                $this->error('陪诊/陪护员审核中');
            if($data['userinfo']['worker_status']=='refused')
                $this->error('陪诊/陪护员审核不通过');
            if($data['userinfo']['worker_status']=='trash'||$data['userinfo']['worker_status']=='deleted')
                $this->error('陪诊/陪护员信息已被冻结');*/

            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录.
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = request()->param('mobile');
        $captcha = request()->param('captcha');
        if (! $mobile || ! $captcha) {
            $this->error('请填写正确的手机号码与验证码');
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('请输入正确的手机号码');
        }
        if (! Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error('验证码错误');
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if ($user) {
            if($user['status']=='writeOff'){
                $this->error('此账号已被注销');
            }
            if ($user->status != 'normal') {
                $this->error('账户被停用');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $worker_info=WorkerInfo::get(['user_id'=>$data['userinfo']['id']])?:[];
            $data['worker_info']=$worker_info;
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员.
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $mobile = request()->param('mobile');
        $password = request()->param('password');
        $code = request()->param('code');
        if (! $mobile || ! $password) {
            $this->error(__('账号密码错误'));
        }

        if ($mobile && ! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号码格式不正确'));
        }

        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('验证码错误'));
        }
        $avatar    = Config::get('site.default_avatar');

        $user_code = self::is_exist(Random::alnum());

        $inviter_code= request()->param('inviter_code','');
        $inviter=[];
        if($inviter_code){
            $inviter=UserModel::where('invitation_code',$inviter_code)->find()?:[];
        }

        $ret = $this->auth->register(
            $mobile,
            $password,
            '',
            $mobile,
            [
                'avatar'=>$avatar,
                'inviter_id'=>$inviter?$inviter['id']:0,
                'invite_code'=>$user_code
            ]
        );
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $worker_info=WorkerInfo::get(['user_id'=>$data['userinfo']['id']])?:[];
            $data['worker_info']=$worker_info;
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录.
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     */
    public function profile()
    {
        $user     = $this->auth->getUser();
        $username   = request()->param('username');
        $avatar     = request()->param('avatar');

        if ($username) {
            $exists = \app\common\model\User::where('username',$username)->where('id','<>',$this->auth->id)->find();
            if ($exists) {
                $this->error(__('昵称已存在!'));
            }
            $user->username = $username;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }

        $user->save();
        $this->success('修改成功');
    }

    /**
     * 修改邮箱.
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = request()->param('captcha');
        if (! $email || ! $captcha) {
            $this->error(__('请填写正确的电子邮箱与验证码'));
        }
        if (! Validate::is($email, 'email')) {
            $this->error(__('请填写正确的电子邮箱'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('此电子邮箱已被其他账号使用'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (! $result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号.
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = request()->param('mobile');
        $captcha = request()->param('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('请填写正确的手机号码与验证码'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号码'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('此手机号码已被其他账号使用'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录.
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = request()->param('platform');
        $code = request()->param('code');
        $config = get_addon_config('third');
        if (! $config || ! isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $mobile = request()->param('mobile');
        $password = request()->param('password');
        $captcha = request()->param('code');
        if (! $password || ! $captcha) {
            $this->error(__('请完善填写信息'));
        }

        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号码错误'));
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if (! $user) {
            $this->error(__('用户不存在'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (! $ret) {
            $this->error(__('验证码错误'));
        }
        Sms::flush($mobile, 'resetpwd');

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($password, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 授权
     */
    public function getUnionId(){
        $code = request()->param('code');
        $type=request()->param('type','user_miniapp');

        if(!$code)
            $this->error('code参数错误');
        if(!in_array($type,['user_miniapp','worker_miniapp']))
            $this->error('平台类型参数错误');

        if($type=='user_miniapp') {
            $appid = config('site.user_miniapp_appid');
            $app_secret = config('site.user_miniapp_appsecret');
        }
        if($type=='worker_miniapp') {
            $appid = config('site.worker_miniapp_appid');
            $app_secret = config('site.worker_miniapp_appsecret');
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$app_secret&js_code=$code&grant_type=authorization_code";

        $result = file_get_contents($url);
        $result = json_decode($result, true);

        if(isset($result['unionid'])){
            $this->success('成功',$result);
        }else{
            if(isset($result['errmsg']))
                $this->error($result['errmsg']);
            $this->error('获取unionid出错');
        }

        $this->error('其他错误');
    }


    /**
     * 微信登录
     */
    public function wxLogin()
    {
        $openid = request()->param('open_id');
        $unionid = request()->param('union_id');


        $type=request()->param('type')?:'user_miniapp';

        if(!$unionid) {
            $this->error('没有登陆信息');
        }

        $user = UserModel::getByWxUnionid($unionid);

        if ($user) {
            if($user['status']=='writeOff'){
                $this->error('此账号已被注销');
            }
            if ($user->status != 'normal') {
                $this->error(__('账号异常!'));
            }
            if($type=='worker_miniapp'&&!in_array($user['pzy_status'],['normal','unpaid'])&&!in_array($user['phy_status'],['normal','unpaid'])){
                if($user['pzy_status']=='refused'||$user['phy_status']=='refused'){
                    $this->error('陪诊/陪护员审核不通过');
                }
                if($user['pzy_status']=='reviewing'||$user['phy_status']=='reviewing'){
                    $this->error('陪诊/陪护员审核中');
                }
                if($user['pzy_status']=='none'&&$user['phy_status']=='none'){
                    $this->error('用户未申请陪诊/陪护员');
                }
                $this->error('陪诊/陪护员信息已被冻结');
            }
            if($type=='user_miniapp'){
                if (!$openid) {
                    $this->error('缺少登陆信息');
                }
                if(!$user['user_wx_miniapp_openid']){
                    $user['user_wx_miniapp_openid']=$openid;
                    $user->save();
                }
            }
            elseif($type=='worker_miniapp'){
                if (!$openid) {
                    $this->error('缺少登陆信息');
                }
                if(!$user['worker_wx_miniapp_openid']){
                    $user['worker_wx_miniapp_openid']=$openid;
                    $user->save();
                }
            }
            else{
                $this->error('用户端类型错误');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);

        } else {

            if($type=='worker_miniapp'){
                $this->error('未找到对应账号，请先登录用户端小程序进行申请');
            }
            if($type=='user_miniapp'){
                if (!$openid) {
                    $this->error('缺少登陆信息');
                }
            }

            $avatar    = Config::get('site.default_avatar');
            $user_code = Random::alnum();
            $user_code = self::is_exist($user_code);

            $invite_code= request()->param('invite_code','');
            $inviter=[];
            if($invite_code){
                $inviter=UserModel::where('invite_code',$invite_code)->find()?:[];
            }

            $extend      = [
                'username'      => '用户'.time().rand(1000,9999),
                'avatar'        => $avatar,
                'invite_code'   => $user_code,
                'inviter_id'    => $inviter?$inviter['id']:0,
                'user_wx_miniapp_openid'    => $openid?:'',
                'wx_unionid'      => $unionid
            ];
            $ret         = $this->auth->wxRegister($unionid,$extend);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $worker_info=WorkerInfo::get(['user_id'=>$data['userinfo']['id']])?:[];
            $data['worker_info']=$worker_info;
            $this->success(__('登陆成功!'),$data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 获取access_token
     */
    public function getAccessToken(){
        $appid = config('site.user_miniapp_appid');
        $app_secret = config('site.user_miniapp_appsecret');
        $api="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$app_secret";

        $result=json_decode(file_get_contents($api),true);

        if(!isset($result['access_token'])||!$result['access_token'])
            $this->error('获取AccessToken出错');

        return $result['access_token'];
    }

    /**
     * 获取微信个人资料
     */
    public function getWxPhone(){
        $code=request()->param('code');
        if(!$code)
            $this->error('code不能为空');

        $access_token=$this->getAccessToken();
        $api="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";

        $data=[
            'code'=>$code
        ];

        $result=Http::sendRequest($api,json_encode($data));

        if(!$result['ret'])
            $this->error($result['info']);

        $response=json_decode($result['msg'],true);

        if($response['errcode']!=0)
            $this->error($response['errmsg']);

        if(!$response['phone_info']['purePhoneNumber'])
            $this->error('获取手机号码为空');

        $this->success('成功',$response['phone_info']['purePhoneNumber']);
    }

    /**
     * 微信绑定手机号账号
     */
    public function wxBind()
    {
        $mobile   = request()->param('mobile');

        $mobile_user = UserModel::getByMobile($mobile);
        $user = $this->auth->getUser();
        if(!$user)
            $this->error('未找到账号信息，请重新注册');

        if($mobile_user){
            $mobile_user['open_id']=$user['open_id'];
            $mobile_user['union_id']=$user['union_id'];
            $mobile_user['inviter_id']=$mobile_user['inviter_id']?:$user['inviter_id'];
            $mobile_user->save();

            if($user['id']!=$mobile_user['id'])
                $user->delete();

            $ret = $this->auth->direct($mobile_user['id']);
        }
        else{
            $user['mobile']=$mobile;
            $user['username']=$user['username']?:$mobile;
            $user['inviter_id']=$user['inviter_id']?:0;
            $user->save();
            $this->auth->direct($user['id']);

            /*$password=Random::numeric(8);
            $this->auth->changepwd($password, '', true);
            \app\common\model\Sms::SendSms($password,$mobile,0,615750);*/
            $ret = $this->auth->direct($user['id']);
        }

        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('登陆成功!'),$data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 判断邀请码是否存在
     *
     * @param string $code
     *
     * @return bool
     */
    public static function is_exist($code)
    {
        $user = UserModel::where('invite_code',$code)->find();
        if ($user) {
            $code = Random::alnum();
            return self::is_exist($code);
        } else {
            return $code;
        }
    }

    /**
     * 收货地址列表
     */
    public function addressList(){
        $id=$this->auth->getUser()['id'];

        $list=Address::where(['user_id'=>$id,'status'=>'normal'])->select()?:[];

        $this->success('成功',$list);
    }

    /**
     * 新增、修改收货地址
     */
    public function addressAdd(){
        $user_id=$this->auth->getUser()['id'];
        $address_id=request()->param('address_id');
        $name=request()->param('name');
        $mobile=request()->param('mobile');
        $address=request()->param('address');
        $lon=request()->param('lon');
        $lat=request()->param('lat');

        if(!$name||!$mobile||!$address)
            $this->error('参数错误');
        if(!$lon||!$lat||$lon=='undefined'||$lat=='undefined'||$lon=='null'||$lat=='null')
            $this->error('经纬度参数错误');

        if($address_id){
            $addr=Address::where(['id'=>$address_id,'user_id'=>$user_id,'status'=>'normal'])->find()?:[];
            if(!$addr)
                $this->error('未找到此地址信息');
        }
        else{
            $addr=new Address();
            $addr['user_id']=$user_id;
        }

        $addr['name']=$name;
        $addr['mobile']=$mobile;
        $addr['address']=$address;
        $addr['lon']=$lon;
        $addr['lat']=$lat;

        $addr->save();

        $this->success('成功');
    }

    /**
     * 删除收货地址
     */
    public function addressDelete(){
        $user_id=$this->auth->getUser()['id'];
        $address_id=request()->param('address_id');

        $addr=Address::where(['id'=>$address_id,'user_id'=>$user_id,'status'=>'normal'])->find()?:[];
        if(!$addr)
            $this->error('未找到此地址信息');

        $addr['status']='deleted';
        $addr->save();

        $this->success('成功');
    }


    /**
     * 监护人关系列表
     */
    public function relationshipList(){

        $list=Relationship::where(['status'=>'normal'])->select()?:[];

        $this->success('成功',$list);
    }


    /**
     * 就诊人信息列表
     */
    public function patientList(){
        $id=$this->auth->getUser()['id'];

        $list=Patient::where(['user_id'=>$id,'status'=>'normal'])->select()?:[];

        $this->success('成功',$list);
    }

    /**
     * 新增、修改就诊人信息
     */
    public function patientAdd(){
        $user_id=$this->auth->getUser()['id'];
        $patient_id=request()->param('patient_id');

        $name=request()->param('name');
        $mobile=request()->param('mobile');
        $id_no=request()->param('id_no');
        $gender=request()->param('gender');
        $relationship_id=request()->param('relationship_id');

        $is_18years=request()->param('is_18years',0);
        $guardian_name=request()->param('guardian_name','');
        $guardian_id_no=request()->param('guardian_id_no','');

        if(!$name||!$mobile||!$id_no||!$gender||!$relationship_id||!in_array((string)$is_18years,['0','1']))
            $this->error('请完善就诊人信息');

        if($is_18years==0||$guardian_name||$guardian_id_no)
            if(!$guardian_name||!$guardian_id_no)
                $this->error('请完善监护人信息');
        
        if($patient_id){
            $patient=Patient::where(['id'=>$patient_id,'user_id'=>$user_id,'status'=>'normal'])->find()?:[];
            if(!$patient)
                $this->error('未找到此就诊人信息');
        }
        else{
            $patient=new Patient();
            $patient['user_id']=$user_id;
        }

        $patient['name']=$name;
        $patient['mobile']=$mobile;
        $patient['id_no']=$id_no;
        $patient['gender']=$gender;
        $patient['is_18years']=$is_18years;

        $patient['relationship_id']=$relationship_id;
        $patient['guardian_name']=$guardian_name;
        $patient['guardian_id_no']=$guardian_id_no;
        
        $patient->save();

        $this->success('成功');
    }

    /**
     * 删除就诊人信息
     */
    public function patientDelete(){
        $user_id=$this->auth->getUser()['id'];
        $patient_id=request()->param('patient_id');

        $patient=Patient::where(['id'=>$patient_id,'user_id'=>$user_id,'status'=>'normal'])->find()?:[];
        if(!$patient)
            $this->error('未找到此就诊人信息');

        $patient['status']='deleted';
        $patient->save();

        $this->success('成功');
    }

    /*
     * 优惠券列表
     */
    public function coupon(){
        $user=$this->auth->getUser();

        $status=request()->param('status');
        $page=request()->param('page')?:1;

        $where=[
            ['user_id','=',$user['id']]
        ];
        if($status=='usable'){
            $where[]=['expire_time','>=',time()];
            $where[]=['use_time','=',0];
        }
        elseif($status=='used'){
            $where[]=['use_time','>',0];
        }
        elseif($status=='expired'){
            $where[]=['expire_time','<',time()];
            $where[]=['use_time','=',0];
        }

        $list=CouponLog::with(['coupon'])
            ->where($where)
            ->order('expire_time asc')
            ->page($page,20)
            ->select();

        $this->success('成功',$list);
    }

    /**
     * 获取绑定信息
     */
    public function bindingInfo()
    {
        $user = $this->auth->getUser();
        $data = [
            'wechat' => ['wx_account' => $user->wx_account?:'','wx_name' => $user->wx_name?:''],
            'alipay' => ['ali_account' => $user->ali_account?:'','ali_name' => $user->ali_name?:''],
        ];
        $this->success('请求成功',$data);
    }

    /**
     * 绑定微信/支付宝
     */
    public function binding()
    {
        $user = $this->auth->getUser();

        $type    = request()->param('type');
        $name    = request()->param('name');
        $account = request()->param('account');

        if (!$type || !in_array($type,['alipay','wechat'])) {
            $this->error("绑定类型错误");
        }

        if (!$name || !$account) {
            $this->error('绑定数据不能为空');
        }

        if(trim($name)=='null'||trim($account)=='null'){
            $this->error('参数不能为字符串"null"');
        }
        if(trim($name)=='undefined'||trim($account)=='undefined'){
            $this->error('参数不能为字符串"undefined"');
        }

        switch ($type) {
            case 'alipay':
                $user->ali_account = $account;
                $user->ali_name    = $name;
                break;
            case 'wechat':
                $user->wx_account = $account;
                $user->wx_name    = $name;
                break;
            default:
                break;
        }

        $result = $user->save();
        if ($result) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }
    }

    /**
     * 提现申请
     */
    public function withdraw()
    {
        $user       = $this->auth->getUser();

        $money = request()->param('money');
        $type   = request()->param('type');

        if (!$money || $money < 0) {
            $this->error("提现金额必须大于0");
        }

        $withdraw_min = Config::get('site.withdraw_min');
        if ($withdraw_min)
            if ($money < $withdraw_min)
                $this->error('最小提现金额: ' . $withdraw_min);

        if (!$type || !in_array($type,['alipay','wechat']))
            $this->error("提现类型错误");

        if ($money > $user['money'])
            $this->error('余额不足');

        if ($type == 'alipay') {
            $paymen_type = '支付宝';
            $account     = $user->ali_account;
            $name        = $user->ali_name;
        }

        if ($type == 'wechat') {
            $paymen_type = '微信';
            $account     = $user->wx_account;
            $name        = $user->wx_name;
        }

        if (!$account || !$name)
            $this->error('请先绑定提现信息');

        $order_sn    = makePaySn($user['id']);

        $memo = '提现' . $money . '元到' . $paymen_type;
        $data = [
            'user_id'    => $user['id'],
            'money'      => $money,
            'type'       => $type,
            'account'    => $account,
            'name'       => $name,
            'memo'       => $memo,
            'order_sn'   => $order_sn,
            'status'     => 'apply'
        ];

        try {
            $result = Withdraw::create($data);
            UserModel::money($money*-1,$user['id'],$memo);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        if ($result) {
            $this->success('申请成功');
        } else {
            $this->error('申请失败');
        }
    }

    /**
     * 余额明细
     */
    public function moneyLog()
    {
        $user=$this->auth->getUser();

        $page=request()->param('page',1)?:1;

        $list=MoneyLog::where(['user_id'=>$user['id']])
            ->order('id desc')
            ->page($page,20)
            ->select()?:[];

        $this->success('成功',$list);
    }

    /**
     * 邀请奖励列表
     */
    public function inviteList()
    {
        $user=$this->auth->getUser();

        $page=request()->param('page',1)?:1;

        /*$list=CouponLog::with(['invitee','coupon'])
            ->where(['user_id'=>$user['id']])
            ->where('invitee_id','<>',0)
            ->order('id desc')
            ->page($page,50)
            ->select()?:[];

        foreach ($list as $l){
            $l->visible([
                '*',
                'invitee'=>['avatar','username','mobile'],
                'coupon'=>['start_money','discount_money']
            ])->toArray();
        }*/

        $list=MoneyLog::with(['invitee'])
            ->where(['user_id'=>$user['id']])
            ->where('invitee_id','<>',0)
            ->order('createtime desc')
            ->page($page,50)
            ->select()?:[];

        foreach ($list as $l){
            $l->visible([
                '*',
                'invitee'=>['avatar','username','mobile'],
            ])->toArray();
        }

        $invite_rules=Config::get('site.invite_rules');

        $this->success('成功',['list'=>$list,'rules'=>$invite_rules?:'']);
    }

    /**
     * 系统通知
     */
    public function notice(){
        $user=$this->auth->getUser();

        $page=request()->param('page',1)?:1;

        $list=Notice::where(['user_id'=>$user['id']])
            ->order('id desc')
            ->page($page,20)
            ->select()?:[];

        $this->success('成功',$list);
    }

/*          '1'=>'已下单','2'=>'已支付','3'=>'已匹配（待接单）','4'=>'已接单','5'=>'服务中','6'=>'已完成','7'=>'双方已评',
            '10'=>'已取消','11'=>'支付超时自动取消','12'=>'失效加时单','15'=>'转单申请中',
            '21'=>'药费待支付','22'=>'药费已支付','23'=>'快递已发出',
            '31'=>'加时服务中',
            '41'=>'退款审核中','42'=>'退款成功','43'=>'退款拒绝'*/
    /*
     * 注销账号
     */
    public function writeOff(){
        $user=$this->auth->getUser();


        //检查是否有未完成的订单
        $where=[
            ['status','in',[1,2,3,4,5,6,7,15,41]],
            ['user_id','=',$user['id']]
        ];
        $user_order=\app\common\model\Order::where($where)->count();
        if($user_order)
            $this->error('您有未完成的订单，请完成订单后再进行注销');

        $worker=WorkerInfo::get(['user_id'=>$user['id']])?:[];
        if($worker){
            $where=[
                ['status','in',[1,2,3,4,5,6,7,15,41]],
                ['worker_id','=',$user['id']]
            ];
            $worker_order= (new \app\common\model\Order)->where($where)->count();
            if($worker_order)
                $this->error('您有未完成的陪诊员订单，请完成订单后再进行注销');
        }

        //检查提现单
        $check_withdraw=Withdraw::where(['user_id'=>$user['id'],'status'=>'apply'])->find();
        if($check_withdraw)
            $this->error('您有正在处理中的提现申请，请等待提现处理后再进行注销');

        $user['status']='writeOff';
        $user->save();
        $this->auth->logout();

        $this->success('成功');
    }

    /**
     * 申请城市代理人
     */
    public function AgentApply(){
        $user=$this->auth->getUser();
        $data=[
            'user_id'       =>$user['id'],
            'name'          =>request()->param('name')?:'',
            'mobile'        =>request()->param('mobile')?:'',
            'city'          =>request()->param('city')?:0,
            'corporation'   =>request()->param('corporation')?:'',
            'profession'    =>request()->param('profession')?:'',
            'msg'           =>request()->param('msg')?:'',
            'status'        =>'reviewing'
        ];

        $agent=CityAgent::where(['user_id'=>$user['id']])->find();
        if($agent&&$agent['status']=1){
            $this->error('您已是城市代理人，请勿重复申请');
        }
        if($agent&&$agent['status']=='deleted'){
            $this->error('城市代理人信息已被停用，请联系客服处理');
        }


        $city=Area::where(['name'=>$data['city']])->find();
        if(!$city){
            $this->error('未找到此城市信息');
        }
        $exist=CityAgent::where(['city'=>$city['id'],'status'=>'normal'])->find();
        if($exist){
            $this->error('此城市已有城市代理，无法申请');
        }
        $data['city']=$city['id'];

        validate('\app\common\validate\CityAgent')->scene('apply')->check($data);

        if($agent){
            CityAgent::update($data,['user_id'=>$user['id']]);
        }
        else{
            $data['create_time']=time();
            CityAgent::insert($data);
        }
        $this->success('成功');
    }
}
